package apiserver

import (
	"cs0512/fmr/internal/apiserver/controller/common"
	"cs0512/fmr/internal/apiserver/controller/user"
	"cs0512/fmr/internal/apiserver/store"
	"cs0512/fmr/internal/pkg/middleware/auth"
	"cs0512/fmr/internal/pkg/response"
	"net/http"

	"github.com/gin-gonic/gin"
)

func initRouter(g *gin.Engine) {
	installMiddleWare(g)
	installController(g)
}

func installMiddleWare(g *gin.Engine) {

}

func installController(g *gin.Engine) {
	g.NoRoute(func(c *gin.Context) {
		response.PageNotFound(c)
	})

	g.StaticFS("/fs", http.Dir("upload"))

	jwtStrage, _ := newJWTAuth().(auth.JWTStrategy)

	storeIns := store.Client()
	commonController := common.New(storeIns)

	// 注册不需要认证的路由
	r := g.Group("/api")
	{
		r.POST("login", jwtStrage.LoginHandler)
		r.POST("logout", jwtStrage.LogoutHandler)
		r.POST("refresh", jwtStrage.RefreshHandler)
		r.POST("/common/secode", commonController.SendSecode)
	}

	r.Use(jwtStrage.AuthFunc())

	initCommonRouter(r, commonController)
	initUserRouter(r, user.NewUserController(storeIns))
}

// 用户接口路由
func initUserRouter(r *gin.RouterGroup, user *user.UserController) {
	ur := r.Group("/user")
	{
		ur.POST("add", user.Create)
		ur.POST("edit", user.Update)
		ur.POST("chpwd", user.ChangePassword)
	}
}

func initCommonRouter(r *gin.RouterGroup, ctl *common.CommonController) {
	cr := r.Group("common")
	{
		cr.POST("/uploadfile", ctl.UploadFile)
		cr.POST("/uploadimage", ctl.UploadImage)
	}
}
